package com.hemaapp.yjnh.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import de.greenrobot.event.EventBus;
import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.uu.view.CharacterParser;
import com.android.uu.view.District;
import com.android.uu.view.PinyinComparator;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.LocationAdapter;
import com.hemaapp.yjnh.db.VisitCitysDBHelper;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.view.ClearEditText;
import com.hemaapp.yjnh.view.LetterListView;
import com.hemaapp.yjnh.view.LetterListView.OnTouchingLetterChangedListener;

/**获取城市列表
 * 
 */
public class CityActivity extends BaseActivity {
	private LinearLayout layoutTitle;
	private TextView titleText;
	private ImageButton titleLeft;
	private Button titleRight;

	private ClearEditText etSearch;
	private LetterListView letterList;
	private ListView mCityList;
	private TextView overlay;

	private HashMap<String, Integer> alphaIndexer;// 存放存在的汉语拼音首字母和与之对应的列表位置
	private Handler handler;
	private OverlayThread overlayThread;
	private WindowManager windowManager;
	/**
	 * 汉字转换成拼音的类
	 */
	private CharacterParser characterParser;
	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparator pinyinComparator;
	private LoacationReceiver loacationReceiver;

	private String locationCity;//当前城市
	private ArrayList<District> allDistricts = new ArrayList<District>();
	private ArrayList<District> visitDistricts;
	private ArrayList<District> filterDateList;
	private LocationAdapter mLocationAdapter;
	
	private int type = -1;//显示的城市类型：1所有地级市，2省份直辖市自治区，3地级市，4县区, 5点击省份后自动到市，点击市自动到县
	private String parentId = "-1";//0：表示获取第一级别（省份或直辖市或自治区） 
									//-1：表示获取所有地级以上级别城市（含地级）
	private String address = "";//用于type=5时，返回省市县的地址信息。

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_city);
		super.onCreate(savedInstanceState);
		init();
	}
	
	private void init() {
		//初始化右侧导航栏
		handler = new Handler();
		overlayThread = new OverlayThread();
		initOverlay();
		initViews();
		//获取城市列表
		districtList();
		if (type == 1) {
			//获取当前所在城市
			getLocationCity();
			//获取历史选择过的城市
			new VisitCityTask().execute();
		}
	}

	// 获取定位城市
	private void getLocationCity() {
		locationCity = XtomSharedPreferencesUtil.get(mContext, "location_city");
		if (isNull(locationCity)) {
			BaseApplication application = BaseApplication.getInstance();
			String action = application.getPackageName() + ".location";
			IntentFilter mFilter = new IntentFilter(action);
			loacationReceiver = new LoacationReceiver();
			registerReceiver(loacationReceiver, mFilter);
		}
	}

	@Override
	protected void onDestroy() {
		windowManager.removeViewImmediate(overlay);
		if (loacationReceiver != null)
			unregisterReceiver(loacationReceiver);
		super.onDestroy();
	}

	private void initViews() {
		// 实例化汉字转拼音类
		characterParser = CharacterParser.getInstance();
		pinyinComparator = new PinyinComparator();
		// 根据输入框输入值的改变来过滤搜索
		etSearch.addTextChangedListener(new TextChageListener());
	}

	/**
	 * 根据输入框中的值来过滤数据并更新ListView
	 * 
	 * @param filterStr
	 */
	private void filterData(String filterStr) {
		filterDateList = new ArrayList<District>();

		if (TextUtils.isEmpty(filterStr)) {
			filterDateList = allDistricts;
		} else {
			filterDateList.clear();
			for (District district : allDistricts) {
				String name = district.getName();
				if (name.indexOf(filterStr.toString()) != -1
						|| characterParser.getSelling(name).startsWith(
								filterStr.toString().toLowerCase(
										Locale.getDefault()))) {
					filterDateList.add(district);
				}
			}
		}
//		boolean isshow = etSearch.isVisibile();
//		mLocationAdapter.setShow(!isshow);
		// 根据a-z进行排序
		Collections.sort(filterDateList, pinyinComparator);
		mLocationAdapter.updateListView(filterDateList);
	}

	// 初始化汉语拼音首字母弹出提示框
	@SuppressLint("InflateParams")
	private void initOverlay() {
		LayoutInflater inflater = LayoutInflater.from(this);
		overlay = (TextView) inflater.inflate(R.layout.overlay, null);
		overlay.setVisibility(View.INVISIBLE);
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_APPLICATION,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
						| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
				PixelFormat.TRANSLUCENT);
		windowManager = (WindowManager) this
				.getSystemService(Context.WINDOW_SERVICE);
		windowManager.addView(overlay, lp);
	}

	private void districtList() {
		getNetWorker().districtList(parentId);
	}

	@Override
	protected void callBeforeDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case DISTRICT_LIST:
			showProgressDialog("请稍候");
			break;
		default:
			break;
		}
	}

	@Override
	protected void callAfterDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case DISTRICT_LIST:
			cancelProgressDialog();
			break;
		default:
			break;
		}
	}

	@Override
	protected void callBackForServerSuccess(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case DISTRICT_LIST:
			@SuppressWarnings("unchecked")
			HemaPageArrayResult<District> dResult = (HemaPageArrayResult<District>) baseResult;
			allDistricts.clear();
			allDistricts.addAll(dResult.getObjects());

			if (type == 1) {
				mLocationAdapter.setLastCties(visitDistricts);
				mLocationAdapter.setLocCity(locationCity);
			}else {//设置不显示当前城市和
				mLocationAdapter.setShow(false);
			}
			
			Collections.sort(allDistricts, pinyinComparator);
			mLocationAdapter.setList(allDistricts);
			setAdapter(allDistricts);
			mLocationAdapter.notifyDataSetChanged();
			break;
		default:
			break;
		}
	}

	/**
	 * 为ListView设置适配器
	 * 
	 * @param list
	 */
	private void setAdapter(List<District> list) {
		if (list != null) {
			mCityList.setAdapter(mLocationAdapter);
			alphaIndexer = mLocationAdapter.getAlphaIndexer();
		}
	}

	@Override
	protected void callBackForServerFailed(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case DISTRICT_LIST:
			
			break;
		default:
			break;
		}
	}

	@Override
	protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case DISTRICT_LIST:
			
			break;
		default:
			break;
		}
	}

	@Override
	protected void findView() {
		layoutTitle = (LinearLayout) findViewById( R.id.layout_title );
		titleText = (TextView) findViewById(R.id.title_text);
		titleLeft = (ImageButton) findViewById(R.id.title_left_btn);
		titleRight = (Button) findViewById(R.id.title_right_btn);

		etSearch = (ClearEditText) findViewById(R.id.etsearch);
		letterList = (LetterListView) findViewById(R.id.letterListView);
		mCityList = (ListView) findViewById(R.id.city_list);
		mLocationAdapter = new LocationAdapter(this, true);
	}

	@Override
	protected void getExras() {
		type = mIntent.getIntExtra("type", -1);
		parentId = mIntent.getStringExtra("parent_id");
	}

	@Override
	protected void setListener() {
		titleText.setText("选择城市");
		titleLeft.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		titleRight.setVisibility(View.GONE);
		letterList
				.setOnTouchingLetterChangedListener(new LetterListViewListener());
		mCityList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				District citysel = (District) view.getTag(R.id.TAG);
				itemclick(citysel);
			}
		});
	}

	/**
	 * 城市列表点击事件
	 * 
	 * 
	 */
	public void itemclick(District info) {
		if (info == null) {
			XtomToastUtil.showShortToast(mContext, "暂不支持此城市");
			return;
		}
		if (type == 5) {
			parentId = info.getId();
			address = address+info.getName();
			String level = info.getLevel();
			if (level.equals("3")) {
				Intent data = new Intent();
				data.putExtra("content", address);
				setResult(RESULT_OK, data);
				finish();
			}else {
				//获取城市列表
				districtList();
			}
		}else {
			Intent data = new Intent();
			saveCityName(info.getName());
			saveCityId(info.getId());
			saveDistrictName(info.getName());
			if (type == 1)
				insertVisitcity(info);
			data.putExtra("parentId", info.getParentid());
			//保存省份
			String[] parentNames = info.getNamepath().split(",");
			data.putExtra("parentName", parentNames[0]);
			//2016.10.27 start 取消全部板块的定位都重置
//			if (type == 1) {//一次选择地址后，替换掉应用中的全部地址
//				XtomSharedPreferencesUtil.save(mContext, "province", parentNames[0]);
//				XtomSharedPreferencesUtil.save(mContext, "city", info.getName());
//			}
			//2016.10.27 end 取消全部板块的定位都重置
			
			setResult(RESULT_OK, data);
			finish();
		}
	}

	private void insertVisitcity(District city) {
		VisitCitysDBHelper dbHelper = new VisitCitysDBHelper(mContext);
		dbHelper.reInsert(city);
	}

	private class LetterListViewListener implements
			OnTouchingLetterChangedListener {

		@SuppressLint("NewApi")
		@Override
		public void onTouchingLetterChanged(final String s) {
			if (alphaIndexer != null && alphaIndexer.get(s) != null) {
				final int position = alphaIndexer.get(s);
				log_w("=s=" + s);
				if (type == 2 || type == 3 || type == 4)
					mCityList.setSelection(position);
				else
					mCityList.setSelection(position + 2);
			} else if ("↑".equals(s)) {
				mCityList.setSelection(0);
			}
			overlay.setText(s);
			overlay.setVisibility(View.VISIBLE);
			handler.removeCallbacks(overlayThread);
			// 延迟一秒后执行，让overlay为不可见
			handler.postDelayed(overlayThread, 1500);
		}

	}

	// 设置overlay不可见
	private class OverlayThread implements Runnable {

		@Override
		public void run() {
			overlay.setVisibility(View.GONE);
		}

	}

	private class VisitCityTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			showProgressDialog("请稍候");
		}

		@Override
		protected Void doInBackground(Void... params) {
			VisitCitysDBHelper dbHelper = new VisitCitysDBHelper(mContext);
			visitDistricts = dbHelper.select();
			return null;
		}

		@Override
		protected void onPostExecute(Void v) {
			cancelProgressDialog();
//			districtList();
		}
	}

	private class LoacationReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			BaseApplication application = BaseApplication.getInstance();
			String realAction = application.getPackageName() + ".location";
			String action = intent.getAction();
			if (realAction.equals(action)) {
				locationCity = XtomSharedPreferencesUtil.get(mContext, "location_city");
				mLocationAdapter.setLocCity(locationCity);
				if (mCityList.getAdapter() != null)
					mLocationAdapter.notifyDataSetChanged();
			}
		}
	}

	private class TextChageListener implements TextWatcher {
		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
			filterData(s.toString());
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void afterTextChanged(Editable s) {
		}
	}
}
